import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ActionSheetController, AlertController, ToastController} from 'ionic-angular';
//地址
import { NewaddressPage } from '../newaddress/newaddress';

import { Https } from '../../app/http.service'


/**
 * Generated class for the AddressPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-address',
  templateUrl: 'address.html',
})
export class AddressPage {
	addressUrl = new Https().Url + "act=goods&op=address_infos"
	delectAddressUrl = new Https().Url + "act=goods&op=app_delect_address"
	isDefaultAddressUrl = new Https().Url + "act=goods&op=app_address_default"
    data: string;  
    class: string = "1";  
    active: string = "actived";  
	addressInfo: Array<{ true_name: string, mob_phone: string, area_info: string, address: string; id: string, is_default:string}>; 
	constructor(public navCtrl: NavController, public navParams: NavParams, public actionSheetCtrl: ActionSheetController, public alertCtrl: AlertController, public toastCtrl: ToastController) {
		
    }

    ionViewDidLoad() {
		console.log('ionViewDidLoad AddressPage 刷新');
		// this.addressInfo = [
			// { name: "强哥", phone: '12312311231', id: '0', check: '1'},
			// { name: "大强哥", phone: '12332113211', id: '1', check: '0'},
			// { name: "小强哥", phone: '12321322311', id: '2', check: '1'},
			// { name: "不大不小强哥", phone: '12345644564', id: '3', check: '0'},
		// ]

		let then = this
		fetch(this.addressUrl, {
			method: "post",
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token"),
		}).then((response) => {
			response.text().then((con) => {
				if (con != ''){
					let resource = JSON.parse(con).datas;
					if (resource != '') {
						then.data = '1';
						then.addressInfo = resource
						then.addressInfo.forEach((val, index) => {
							then.addressInfo[index]['id'] = index.toString();
						})
						then.addressInfo.forEach((val, id) => {
							if (val.is_default == '1') {
								then.addressInfo.splice(id, 1)
								then.addressInfo.unshift(val)
							}

						})
						then.addressInfo.forEach((val, id) => {
							if (val.is_default == '1') {
								then.class = id.toString();
							}
						})
					} else {
						then.data = '0';
					}
				} else {
					then.data = '0';
				}
				
				
				console.log(then.addressInfo)
			})
		}).catch((err) => {
			this.alertPop(err)
		})

		
    }
    newPage(){
      	this.navCtrl.push(NewaddressPage);
	}
	
	changeDefault(list){
		this.class = list
		console.log(this.addressInfo[list]["address_id"])
		fetch(this.isDefaultAddressUrl,{
			method:"post",
			headers:{
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token") + "address_id=" + this.addressInfo[list]["address_id"]
		}).then((response)=>{
			response.text().then((res)=>{
				
				let Data = JSON.parse(res)
				console.log(Data)
				console.log(Data.datas.status)
				if (Data.datas.status == 0){
					this.alertPop("哎呀！出错了")
				}
			})
		}).catch((res)=>{
			this.alertPop("哎呀！出错了")
		})
	}

	editAddress(){
		console.log("123");
	}

	delete(id){
		let actionSheet = this.actionSheetCtrl.create({
			title: '地址删除后，不可再使用该地址',
			buttons: [
				{
					text: '确认删除',
					cssClass:'alert',
					handler: () => {
						console.log('delete', id);
						this.delectAddress(id)
					}
				},
				{
					text: '取消',
					role: 'cancel',
					cssClass: 'cancel',
				}
			]
		}); actionSheet.present();
	}

	//删除地址
	delectAddress(id){
		let then = this
		fetch(this.delectAddressUrl, {
			method: "post",
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token")+"&id="+id,
		}).then((response) => {
			response.text().then((con) => {
				if(con != ''){
					let resource = JSON.parse(con).datas;
					if (resource.code == 3){
						this.alertPop("删除失败")
					}else{
						let toast = this.toastCtrl.create({
							message: '删除成功',
							duration: 3000
						});
						toast.present();
					}
					console.log(resource)
				}else{
					this.alertPop("网络出错")
				}
			})
		}).catch((err) => {
			
			this.alertPop(err)
		})
	}
	//下拉刷新
	doRefresh(refresher) {
		console.log('Begin async operation', refresher);
		this.ionViewDidLoad()
		setTimeout(() => {
			refresher.complete();
		}, 2000);
	}
	//出错
	alertPop(err){
		let confirm = this.alertCtrl.create({
			title: '温馨提示',
			message: err,
			buttons: [
				{ text: '确定' },

			]
		});
		confirm.present();
	}

}
